//
// Created by v on 19-7-23.
//

#include "opencv2/opencv.hpp"
#include <stdio.h>
#include <unistd.h>

int doCatchFrame(const char *filename, const char *pos)
{
    cv::VideoCapture cap(filename);
    if (cap.isOpened())
    {
        cv::Mat     mat;
        char        savepos[1024] = {0};
        const char *s             = filename;
        char *      ss            = (char *)rindex(s, '/');
        if (ss)
        {
            ss++;
        }
        else
        {
            ss = (char *)s;
        }
        char * se            = index(ss, '.');
        size_t len           = se - ss - 1;
        char   basename[512] = {0};
        strncpy(basename, ss, len);
        int count = 0;
        while (true)
        {
            bool r = cap.read(mat);
            if (!r)
                break;

            sprintf(savepos, "%s/%s-%d.jpg", pos, basename, count);
            printf("Will save file to [%s]\n", savepos);
            cv::imwrite(savepos, mat);
            count++;
            usleep(40000);
        }
    }
    else
    {
        printf("Error: open file failed\n");
        return -1;
    }

    return 0;
}

int main(int argc, char **args)
{
    if (argc < 3)
    {
        printf("Usage: %s [filename] [save position]\n", args[0]);
        return 1;
    }
    const char *filename = args[1];
    const char *pos      = args[2];

    printf("Do with filename [%s] save to [%s]\n", filename, pos);
    return doCatchFrame(filename, pos);
}